<?php
namespace app\manage\controller;

use app\manage\controller\BaseController;
use think\facade\Db;
use think\facade\View;
use app\manage\model\Cate as Catemodel;
use app\manage\model\Download as Downloadmodel;

class Download extends BaseController
{
    public function index()
    {
		$data=input('get.');
		if(!isset($data['key'])){
			$data['key']='';
		}
        View::assign('data', $data);
		$info=Downloadmodel::where('title', 'like', '%'.$data['key'].'%')
		->order('id desc')
		->paginate(10,false,['query'=>request()->param()]);
        View::assign('info', $info);
        View::assign('count1', $info->total());
        return View::fetch();
    }
    public function ajax()
    {
        $data=input('post.');
        $download=new Downloadmodel();
        if ($data['type']=='download_del') {
            if ($download->destroy($data['id'])) {
                return json(['code' => 1, 'message' => '操作成功']);
            } else {
                return json(['code' => 0, 'message' => '操作失败']);
            }
        }
        if ($data['type']=='download_all') {
            if ($download->destroy($data['id'])) {
                return json(['code' => 1, 'message' => '操作成功']);
            } else {
                return json(['code' => 0, 'message' => '操作失败']);
            }
        }
		if($data['type']=='download_start'){
			if($download->where('id',$data['id'])->update(['isopen'=>1])){
                return json(['code' => 1, 'message' => '操作成功']);
            } else {
                return json(['code' => 0, 'message' => '操作失败']);
            }
		}
		if($data['type']=='download_stop'){
			if($download->where('id',$data['id'])->update(['isopen'=>0])){
                return json(['code' => 1, 'message' => '操作成功']);
            } else {
                return json(['code' => 0, 'message' => '操作失败']);
            }
		}
        return json(['code'=>0]);
    }
    public function add()
    {
        if (request()->isPost()) {
            $data=input('post.');
            $validate = new \app\manage\validate\Download;
            if (!$validate->check($data)) {
                $this->error($validate->getError());
            }
            if (!isset($data['is_tui'])) {
                $data['is_tui']=0;
            } else {
                $data['is_tui']=1;
            }
            if ($data['create_time']) {
                $data['create_time']=strtotime($data['create_time']);
            }else{
                unset($data['create_time']);
            }
            $file = request()->file('');
			if (isset($file['file'])) {
                try {
                    validate(['file'=>'fileSize:47185920'])->check($file);
                    $info=\think\facade\Filesystem::disk('public')->putFile( 'download', $file['file']);
                    $data['file']='/storage/'.strtr($info, " \ ", " / ");
                } catch (\think\exception\ValidateException $e) {
                    $this->error($e->getMessage());
                }
			}else{
				$this->error('请添加附件！');
			}
            if (isset($file['pic'])) {
                try {
                    validate(['pic'=>'fileSize:5242880|fileExt:jpg,png,gif,webp,jpeg'])->check($file);
                    $info=\think\facade\Filesystem::disk('public')->putFile( 'download', $file['pic']);
                    $data['pic']='/storage/'.strtr($info, " \ ", " / ");
                } catch (\think\exception\ValidateException $e) {
                    $this->error($e->getMessage());
                }
            } 
			
            if (input('desc')=='') {
                $data['desc']=mb_substr(preg_replace('/\&nbsp;/', '', strip_tags(input('text'))), 0, 200);
            }
			
			preg_match_all("/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg|\.png]))[\'|\"].*?[\/]?>/", $data["text"], $arr);
			$config=Db::name('config')->column('value', 'key');
			//压缩图片
			foreach ($arr[1] as $k=>$v) {
			    if (substr($v, 0, 4)!='http' and is_file(substr($v, 1))) {
			        $newarr=getimagesize(substr($v, 1));
				   if ($config["is_ya"] ==1 and $newarr[0] >$config["ya_w"]) {
				      $image = \think\Image::open(substr($v, 1));
				      $h=$config["ya_w"]*$newarr[1]/$newarr[0];
				      $image->thumb($config['ya_w'],$h)->save(substr($v, 1));
							
				   }
			    }
			}
            $data['faid']=session('uid');
            if (Downloadmodel::create($data)) {
                return '<script>alert("你好，添加成功了！");parent.location.reload()</script>';
            } else {
                $this->error('添加失败了');
            }
        }
        return View::fetch();
    }
    public function edit()
    {
        if (request()->isPost()) {
            $data=input('post.');
            $validate = new \app\manage\validate\Download;
            if (!$validate->scene('edit')->check($data)) {
                $this->error($validate->getError());
            }
            if (!isset($data['is_tui'])) {
                $data['is_tui']=0;
            } else {
                $data['is_tui']=1;
            }
            if ($data['create_time']) {
                $data['create_time']=strtotime($data['create_time']);
            }else{
                unset($data['create_time']);
            }
            if (input('desc')=='') {
                $data['desc']=mb_substr(preg_replace('/\&nbsp;/', '', strip_tags(input('text'))), 0, 200);
            }
            $file = request()->file('');
			if (isset($file['file'])) {
                try {
                    validate(['file'=>'fileSize:47185920'])->check($file);
                    $info=\think\facade\Filesystem::disk('public')->putFile( 'download', $file['file']);
                    $data['file']='/storage/'.strtr($info, " \ ", " / ");
                } catch (\think\exception\ValidateException $e) {
                    $this->error($e->getMessage());
                }
			}
            if (isset($file['pic'])) {
                try {
                    validate(['pic'=>'fileSize:5242880|fileExt:jpg,png,gif,webp,jpeg'])->check($file);
                    $info=\think\facade\Filesystem::disk('public')->putFile( 'download', $file['pic']);
                    $data['pic']='/storage/'.strtr($info, " \ ", " / ");
                } catch (\think\exception\ValidateException $e) {
                    $this->error($e->getMessage());
                }
            }
			preg_match_all("/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg|\.png]))[\'|\"].*?[\/]?>/", $data["text"], $arr);
			$config=Db::name('config')->column('value', 'key');
			//压缩图片
			foreach ($arr[1] as $k=>$v) {
			    if (substr($v, 0, 4)!='http' and is_file(substr($v, 1))) {
			        $newarr=getimagesize(substr($v, 1));
				   if ($config["is_ya"] ==1 and $newarr[0] >$config["ya_w"]) {
				      $image = \think\Image::open(substr($v, 1));
				      $h=$config["ya_w"]*$newarr[1]/$newarr[0];
				      $image->thumb($config['ya_w'],$h)->save(substr($v, 1));
				   }
			    }
			}
            $res=Downloadmodel::update($data, ['id' => input('id')]);
            if ($res) {
                return $this->success('修改成功', url('download/index',['st'=>1]));
            } else {
                return $this->error('修改失败了');
            }
        }
        $cid=input('id',0);
        $data=Db::name('download')->where('id', $cid)->find();
        View::assign('data', $data);
        return View::fetch();
    }
}
